package com.xqkad.myfile.ui;

import android.Manifest;
import android.app.*;
import android.content.*;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.provider.DocumentFile;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.*;
import android.widget.*;

import com.xqkad.myfile.*;
import com.xqkad.myfile.tools.*;

import java.lang.ref.WeakReference;
import java.util.*;

public class MainActivity extends AppCompatActivity {
    private TextView tv1, tv_paste, tv_new;
    private ListView lv1;
    private MyAdapter arrayAdapter;
    private ProgressDialog pd;
    private AlertDialog dg;

    private ArrayList<String> currentPaths = new ArrayList<String>();
    private ArrayList<String> selectPaths = new ArrayList<String>();
    private ArrayList<String> selectNames = new ArrayList<String>();
    private boolean isPaste = false;

    private MyHandler handler = new MyHandler(this);
    static class MyHandler extends Handler{
        WeakReference<MainActivity> weakRef;
        public MyHandler(MainActivity activity){
            this.weakRef = new WeakReference<>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = this.weakRef.get();
            if(activity != null){
                activity.onHandleMessage(msg);
            }
        }
    };
    public void onHandleMessage(Message msg) {
        switch (msg.what) {
            case 1://finish
                if(pd != null && pd.isShowing()){
                    pd.dismiss();
                    isPaste = false;
                    selectNames.clear();
                    selectPaths.clear();
                    setFileItemsAdapter(false, true, true);
                }
                break;
            case 2://update progress
                if(pd != null && pd.isShowing())
                    pd.setProgress(msg.arg1);
                break;
            case 3://dg msg
                String[] ss = (String[])msg.obj;
                if(ss == null || ss.length!=2)
                    return;
                startDgMsg(ss[0], ss[1]);
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1 = findViewById(R.id.tv1);
        tv_paste = findViewById(R.id.tv_paste);
        tv_new = findViewById(R.id.tv_new);
        lv1 = findViewById(R.id.lv1);
        lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(currentPaths.size()==0)
                    onMainAdapterClick(adapterView, view, i, l);
                else
                    onArrayAdapterClick(adapterView, view, i, l);
            }
        });
        //if(test7()) return;
        restory(savedInstanceState);
        checkPermissing();
        init();
    }

    void checkPermissing(){
        int writePermission = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            writePermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (writePermission != PackageManager.PERMISSION_GRANTED) {
                //Log.v(TAG,"测试手机版本为：android 6.0以上--->未申请--->申请读写权限");
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
            }else{
                //Log.v(TAG,"测试手机版本为：android 6.0以上--->已申请");
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            if(!getPackageManager().canRequestPackageInstalls()){
                startActivity(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES));
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null || resultCode != RESULT_OK)
            return;
        DocumentFile df;
        String struri, name;
        if(requestCode ==1 || requestCode==2){
            struri = data.getData().toString();
            if(struri.length() != 65){
                sc("选择错误");
                return;
            }
            df = DocumentFile.fromTreeUri(this, data.getData());
            name = df.getName();
            //sc(name+" ");
            if(MySAF.getStoragePaths(this)[requestCode].endsWith(name)){
                MySAF.saveUri(this,struri,requestCode);
                setStorageItemsAdapter();
            }else sc("选择错误");
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putStringArrayList("currentPaths",currentPaths);
        outState.putStringArrayList("selectPaths",selectPaths);
        outState.putStringArrayList("selectNames",selectNames);
        outState.putBoolean("isPaste", isPaste);
        //outState.putBoolean("isStorageList", isStorageList);
        super.onSaveInstanceState(outState);
    }


    @Override
    public void onBackPressed() {
        int size = currentPaths.size();
        if(size != 0){
            currentPaths.remove(size-1);
            if(size == 1) setStorageItemsAdapter();
            else setFileItemsAdapter(false, false, false);
        }else super.onBackPressed();
    }

    private void restory(Bundle bundle){
        if(bundle == null)
            return;

        currentPaths = bundle.getStringArrayList("currentPaths");
        selectPaths = bundle.getStringArrayList("selectPaths");
        selectNames = bundle.getStringArrayList("selectNames");
        isPaste = bundle.getBoolean("isPaste");
        //isStorageList = bundle.getBoolean("isStorageList");
    }

    private void init(){
        int size = currentPaths.size();
        if(size == 0){
            setStorageItemsAdapter();
        }else{
            setFileItemsAdapter(true, true, false);
        }
    }

    private void setStorageItemsAdapter(){
        //isStorageList = true;
        tv_paste.setVisibility(TextView.INVISIBLE);
        tv_new.setVisibility(TextView.INVISIBLE);
        String uri1, uri2, sdsize, usbsize;
        ArrayList<String> list = new ArrayList<String>();
        uri1 = MySAF.getSdUri(this);
        uri2 = MySAF.getUpanUri(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if(MySAF.getStoragePaths(this).length > 1)
                sdsize = StorageList.getPathSize(MySAF.getStoragePaths(this)[1], 1);
            else
                sdsize = "0";
            if(MySAF.getStoragePaths(this).length > 2)
                usbsize = StorageList.getPathSize(MySAF.getStoragePaths(this)[2], 1);
            else
                usbsize = "0";
        }else{
            sdsize = "0";
            usbsize = "0";
        }

        list.add("内部存储");
        if(!sdsize.equals("0")){
            if(uri1 == null || uri1.equals("")){
                list.add("sd卡(点击授权)");
            }else{
                DocumentFile sddf = DocumentFile.fromTreeUri(this, Uri.parse(uri1));
                if(sddf != null && sddf.canWrite()) list.add("sd卡");
                else list.add("sd卡(点击授权)");
            }
        }
        if(!usbsize.equals("0")){
            if(uri2 == null || uri2.equals("")){
                list.add("U盘(点击授权)");
            }else{
                DocumentFile usbdf = DocumentFile.fromTreeUri(this, Uri.parse(uri2));
                if(usbdf != null && usbdf.canWrite()) list.add("U盘");
                else list.add("U盘(点击授权)");
            }
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                R.layout.str_adapter, list);
        lv1.setAdapter(adapter);
        lv1.setChoiceMode(ListView.CHOICE_MODE_NONE);
        sc("");
    }

    private void setFileItemsAdapter(boolean setadapter, boolean setmode, boolean setSelection){
        ArrayList<ItemData> list = MySAF.openPath(currentPaths, this);
        if(arrayAdapter == null){
            arrayAdapter = new MyAdapter(list, this);
            lv1.setMultiChoiceModeListener(new OnMultiChoice(arrayAdapter));
        }else{
            arrayAdapter.setData(list);
            arrayAdapter.notifyDataSetChanged();
        }
        if(setadapter){
            lv1.setAdapter(arrayAdapter);
            tv_new.setVisibility(TextView.VISIBLE);
        }
        if(setmode && !isPaste)
            lv1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        if(setSelection)
            lv1.setSelection(0);
        if(isPaste) tv_paste.setVisibility(TextView.VISIBLE);
        else tv_paste.setVisibility(TextView.INVISIBLE);
        sc(currentPaths.get(currentPaths.size()-1));
    }

    public void onClick(View view) {
        if(view.getId() == R.id.tv_paste){
            isPaste = false;
            startPD();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    MySAF.copy(currentPaths, selectPaths, selectNames, MainActivity.this, handler);
                }
            }).start();
        }else if(view.getId() == R.id.tv1){
            if(currentPaths.size()>0)
                onBackPressed();
        }else if(view.getId() == R.id.tv_new){
            lv1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
            String[] items = new String[] {"文件夹", "文件"};
            AlertDialog log =
                    new AlertDialog.Builder(MainActivity.this)
                            .setItems(items, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    if(i == 0){
                                        MySAF.newDir(currentPaths, MainActivity.this);
                                    }else if(i == 1){
                                        MySAF.newFile(currentPaths, MainActivity.this);
                                    }
                                    setFileItemsAdapter(false, false, true);
                                }
                            }).create();
            log.show();
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
                    R.layout.str_adapter, items);
            log.getListView().setAdapter(adapter);
        }
    }

    public void onMainAdapterClick(AdapterView<?> adapterView, View view, int i, long l){
        String str = (String)adapterView.getItemAtPosition(i);
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        if(str.equals("sd卡(点击授权)")){
            startActivityForResult(intent,1);
        }else if(str.equals("U盘(点击授权)")){
            startActivityForResult(intent,2);
        }else{
            currentPaths.add(str);
            setFileItemsAdapter(true, true, true);
        }
    }

    public void onArrayAdapterClick(AdapterView<?> adapterView, View view, int i, long l){
        ItemData data = (ItemData)adapterView.getItemAtPosition(i);
        String str = data.getText();
        if(data.getImageid() == R.mipmap.wenjianjia){
            currentPaths.add(str);
            setFileItemsAdapter(false, false, true);
            lv1.setSelection(0);
        }else{
            Intent intent = MySAF.openFile(this, currentPaths, str);
            if(intent != null)
                startActivity(intent);
            else
                startDgMsg("", "无法打开");
            //
        }
    }


    public void sc(String str){
        if(str != null)
            tv1.setText(str);
    }

    public void sc(String str, int a){
        if(str != null)
            tv1.append(str);
    }

    private void setSelectNamesAndPath(){
        selectPaths.clear();
        for(String s : currentPaths){
            selectPaths.add(s);
        }
        selectNames.clear();
        long[] ls = lv1.getCheckedItemIds();
        SparseBooleanArray sp = lv1.getCheckedItemPositions();
        for (int i=0;i<sp.size();i++){
            int key = sp.keyAt(i);
            if(sp.get(key)){
                ItemData data = (ItemData) lv1.getItemAtPosition(key);
                String text = data.getText();
                selectNames.add(text);
            }
        }
    }

    private void startPD(){
        if(pd == null)
            pd = new ProgressDialog(MainActivity.this);
        pd.setMax(100);
        //pd.setMessage("123123");
        pd.setIndeterminate(false);
        pd.setCancelable(false);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        //pd.setVolumeControlStream(TRIM_MEMORY_BACKGROUND);
        pd.show();
    }

    private void startDgRename(){
        String text = selectNames.get(0);
        MyDialog.showEditDg(this, text, new MyDialog.OnYesEdit() {
            @Override
            public void onYesEdit(String text) {
                MySAF.rename(currentPaths, selectNames, MainActivity.this, text);
                setFileItemsAdapter(false,true,false);
            }
        });
    }

    private void startDgYesOrNoDelete(){
        String text = "删除: "+selectNames.get(0)+" "+selectNames.size()+"个文件";
        this.dg = MyDialog.showYesOrNoDg(this, text, new Runnable() {
            @Override
            public void run() {
                startPD();
                MySAF.delete(currentPaths, selectNames, MainActivity.this, handler);
            }
        });
    }

    private void startDgMsg(String msg, String title){
        if(this.dg != null && this.dg.isShowing())
            this.dg.dismiss();
        this.dg = MyDialog.showMsgDg(this,msg, title);
        lv1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    }

    private void log(){
        //String str = MyIO.readString("/storage/sdcard1/aa/lol/dd/m234.txt");
        //MyIO.writeString("/storage/emulated/0/xqkad/pz.txt", str);
        String cp="", sp="", sn="";
        for(String s : currentPaths){
            cp = cp+s+" ";
        }
        for(String s : selectPaths){
            sp = sp+s+" ";
        }
        for(String s : selectNames){
            sn = sn+s+" ";
        }
        Log.d("mytag",cp);
        Log.d("mytag",sp);
        Log.d("mytag",sn);
    }

    class OnMultiChoice implements AbsListView.MultiChoiceModeListener{
        MyAdapter adapter;
        View actionBarView ;
        TextView tv_select, tv_all;
        CheckBox cb;

        public OnMultiChoice(MyAdapter adapter){
            this.adapter = adapter;
        }

        @Override
        public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
            MyAdapter.cb_show = true;
            if(actionBarView == null) {
                actionBarView = LayoutInflater.from(MainActivity.this).inflate(R.layout.actionbar, null);
                cb = (CheckBox)actionBarView.findViewById(R.id.cb_all);
                tv_select = (TextView)actionBarView.findViewById(R.id.tv_select);
                tv_all = (TextView)actionBarView.findViewById(R.id.tv_all);
                tv_all.setOnClickListener(new View.OnClickListener(){
                    @Override
                    public void onClick(View view) {
                        setSelectNamesAndPath();
                        if(selectNames.size() == lv1.getCount()){
                            adapter.setAllCheck(false);
                            adapter.notifyDataSetChanged();
                            lv1.clearChoices();
                            tv_select.setEnabled(false);
                            tv_select.setTextColor(Color.BLACK);
                            cb.setChecked(false);
                        }else{
                            for(int i = 0;i<lv1.getCount();i++){
                                lv1.setItemChecked(i,true);
                            }
                            cb.setChecked(true);
                        }
                    }
                });
                tv_select.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String[] items = new String[] {"复制", "重命名", "删除", "大小"};
                        setSelectNamesAndPath();
                        //int size = selectNames.size();
                        AlertDialog log =
                        new AlertDialog.Builder(MainActivity.this)
                                .setItems(items, new DialogListener()).create();
                                log.show();
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
                                R.layout.str_adapter, items){
                            @Override
                            public boolean isEnabled(int position) {
                                if(position == 1 && selectNames.size() != 1)
                                    return false;
                                return super.isEnabled(position);
                            }

                            @NonNull
                            @Override
                            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                                TextView tv = (TextView)super.getView(position, convertView, parent);
                                if(position == 1 && selectNames.size() != 1){
                                    tv.setTextColor(Color.BLACK);
                                }else tv.setTextColor(Color.WHITE);
                                return tv;
                            }
                        };

                        adapter.isEnabled(1);
                        log.getListView().setAdapter(adapter);
                    }
                });
            }
            actionMode.setCustomView(actionBarView);
            return true;
        }

        @Override
        public void onItemCheckedStateChanged(ActionMode actionMode, int i, long l, boolean b) {
            adapter.setItemCheck(i, b);
            actionMode.invalidate();
            adapter.notifyDataSetChanged();
            if(b && !tv_select.isEnabled()){
                tv_select.setEnabled(true);
                tv_select.setTextColor(Color.WHITE);
            }
            if(!b)
                cb.setChecked(false);
        }

        @Override
        public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
            return true;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {
            MyAdapter.cb_show = false;
            adapter.setAllCheck(false);
        }
    }

    class DialogListener implements DialogInterface.OnClickListener{

        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            //setSelectNamesAndPath();
            switch(i){
                case 0:
                    isPaste = true;
                    lv1.setChoiceMode(ListView.CHOICE_MODE_NONE);
                    break;
                case 1:
                    startDgRename();
                    break;
                case 2:
                    startDgYesOrNoDelete();
                    break;
                case 3:
                    startDgMsg("正在计算", null);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            MySAF.size(currentPaths, selectNames, MainActivity.this, handler);
                        }
                    }).start();
                break;
            }
        }
    }
}
